var xzlp_app = function(){
	var ywy = manager.findParamFromUrl("ywy") || "000000"; 
	var lmxxParam = {
			ywy: ywy
	};
	var lpid = manager.findParamFromUrl("lpid")
	var lmcj = 1;
	var lpLogo = {}, lpsltList = [], sltList = [];
	var logoUploader, sltUploader;
	var xglpRactive, editor;
	var toolbars = [ [ 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', '|', 'forecolor', 'backcolor', '|', 'fontfamily', 'fontsize', '|',
	       			'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', 'preview', 'simpleupload', 'insertvideo', '|' ] ];
	
	function loadXzlp(){
		$.get("../../tpl/lpgl/lpgl-xz-tpl.html", function(template){
			xglpRactive = new Ractive({
				el: ".hp-container",
				template: template,
				data: {
					pic: Constants.imageUrl
				},
				oncomplete: function(){
					$("#title").html("Modify the gift")
					
					uploadLogo();
					//长传缩略图
					uploadSlt();
					
					//获取礼品详情
					getLpxq();
				}
			});
			xglpRactive.on({
				xzlp: function(e){
					var lplmid;
					if(!$("#lpgl_LPLMSIJ").attr("disabled")){
						lplmid = getWDCode("lpgl_LPLMSIJ");
					}else if(!$("#lpgl_LPLMSJ").attr("disabled")){
						lplmid = getWDCode("lpgl_LPLMSJ");
					}else if(!$("#lpgl_LPLMEJ").attr("disabled")){
						lplmid = getWDCode("lpgl_LPLMEJ");
					}else if(!$("#lpgl_LPLMYJ").attr("disabled")){
						lplmid = getWDCode("lpgl_LPLMYJ");
					}
					if(lpsltList){
						for(var i=0,len=lpsltList.length; i<len; i++){
							lpsltList[i].sx = i;
						}
					}

					var lpmc = $.trim(xglpRactive.get("lpgl.lpmc"));
					xglpRactive.set("lpgl.lpmc", lpmc);
					var lpxxParam = {
							id : lpid,
							lpmc : $.trim(xglpRactive.get("lpgl.lpmc")),
						    sfxn : xglpRactive.get("lpgl.sfxn"), //  是否虚拟，可不传
						    lplmid: lplmid,
						    lpLogo: lpLogo,
						    lpsltList: lpsltList,
						    jf : xglpRactive.get("lpgl.jf"),
						    lpsl : xglpRactive.get("lpgl.lpsl"),
						    lpbq : getWDCode("lpgl_LPBQ"),
						    lpxxjs: editor.getContent(),
						    ywy: ywy
					};
					
					if(!lpxxParam.lpmc){
						alert("Gift name can not be empty!");
						return;
					}
					if(!lpxxParam.sfxn){
						alert("Select the gift type!");
						return;
					}
					if(!lpxxParam.lplmid){
						alert("Select the gift category!");
						return;
					}
					if($.isEmptyObject(lpLogo)){
						alert("Upload gift LOGO!");
						return;
					}
					if($.isEmptyObject(lpsltList)){
						alert("Upload gift thumbnail!");
						return;
					}
					if(lpxxParam.jf === ""){
						alert("Exchange school coin can not be empty!");
						return;
					}
					if(lpxxParam.lpsl === ""){
						alert("Gift amount can not be empty!");
						return;
					}
					if(lpxxParam.lpsl<=parseInt(xglpRactive.get("lpgl").dhsl)){
						alert("The gift was exchanged"+xglpRactive.get("lpgl").dhsl+"items, the setting gift amount must be greater than the exchanged amount! ");
						return;
					}
					var wyParam = {
							lpmc: lpxxParam.lpmc,
							id: lpid,
							ywy:ywy
					};
					var qrParam = {
							txt: "Confirm modify gift?",
							successCallBackFun: function(){
								$.ajax({
									type: "post",
									url: Constants.amUrlPath+"lpgl/validateLpmc",
									data: JSON.stringify(wyParam),
									dataType: "json",
									contentType: "application/json",
									success: function(data){
										if(data.result){
											$.ajax({
												type: "post",
												url: Constants.amUrlPath+"lpgl/updateLpxx",
												data: JSON.stringify(lpxxParam),
												dataType: "json",
												contentType: "application/json",
												success: function(data){
													if(data.result){
														var sucObj = {
																txt: "Saved successfully!",
																callBackFun: function(){
																	location.href = "lpgl.html";
																}
														}
														success(sucObj);
													}else{
														manager.errorMsg(data);
													}
												}
											})
										}else{
											alert("The gift name already exists, please rename it!")
										}
									}
								});
							}
					}
					confirm(qrParam);
				},
				qx: function(){
					location.href = "lpgl.html";
				},
				zy: function(e){
					var i = e.index.i;
					if(i>0){
						var dqA = lpsltList[i];
						lpsltList[i] = lpsltList[i-1];
						lpsltList[i-1] = dqA;
						
						xglpRactive.set("sltList", lpsltList);
					}
				},
				yy: function(e){
					var i = e.index.i;
					var len = lpsltList.length - 1;
					if(i<len){
						var dqA = lpsltList[i];
						lpsltList[i] = lpsltList[i+1];
						lpsltList[i+1] = dqA;
						
						xglpRactive.set("sltList", lpsltList);
					}
				},
				sc: function(e){
					var i = e.index.i;
					lpsltList.splice(i, 1);
					
					xglpRactive.set("sltList", lpsltList);
				},
				jc: function(e){
					var val = $(e.node).val();
					val = val.replace(/\D/g, "");
					if($(e.node).attr("name") == "dhsxjf"){
						xglpRactive.set("lpgl.jf", val);
					}else{
						xglpRactive.set("lpgl.lpsl", val);
					}
				}
			})

		})
	}
	function getLpxq(){
		$.ajax({
			type: "get",
			url: Constants.amUrlPath+"lpgl/getLpxxByLpid?lpid="+lpid+"&ywy="+ywy+"&time="+new Date(),
			success: function(data){
				xglpRactive.set("lpgl", data);
				lpsltList = data.lpsltList;
				lpLogo = data.lpLogo;
				$("#hp-logo-upload").css("background", "url("+Constants.imageUrl+lpLogo.fjdz+") no-repeat center");
				$("#hp-logo-upload").css("background-size", "150px 96px");
				xglpRactive.set("sltList", lpsltList);
				//获取礼品目录
				getLpml(data.lplmid);
				//获取礼品标签
				getLpbq(data.lpbq);
				//简介
				editor = new baidu.editor.ui.Editor({
					toolbars : toolbars,
					autoHeightEnabled : false,
					initialContent:data.lpxxjs
				});
				editor.render('lpjj');
			}
		})
	}
	
	//根据礼品目录id获取礼品目录
	function getLpml(lmid){
		$.ajax({
			type: "post",
			url: Constants.amUrlPath+"common/getLmxxList",
			data: JSON.stringify(lmxxParam),
			dataType: "json",
			contentType: "application/json",
			async: false,
			success: function(data){
				getSjLpml(data, lmid);
			}
		})
	}
	function getSjLpml(data, lmid){
		for(var i=0,len=data.length; i<len; i++){
			if(data[i].code == lmid){
				 var flmid = data[i].flmid;
				 lmcj = data[i].lmjb;
				 if(lmcj == "1"){
					 /*store.set("LPLMYJ", JSON.stringify(data))
					 selecttextInfo();*/
					 getLmxx({flmid: 0, lmjb: "1", ywy: ywy},'LPLMYJ');
					 setWDCode("lpgl_LPLMYJ", lmid);
				 }else if(lmcj == "2"){
					 getEjlpml(flmid);
					 setWDCode("lpgl_LPLMEJ", lmid);
					 getSjLpml(data, flmid);
				 }else if(lmcj == "3"){
					 getSjlpml(flmid);
					 setWDCode("lpgl_LPLMSJ", lmid);
					 getSjLpml(data, flmid);
				 }else if(lmcj == "4"){
					 getSijlpml(flmid);
					 setWDCode("lpgl_LPLMSIJ", lmid);
					 getSjLpml(data, flmid);
				 }
				 
			}
		}
	}
	
	function getEjlpml(flmid){
		if(getWDCode("lpgl_LPLMEJ")){
			setWDCode("lpgl_LPLMEJ", "");
			if(getWDCode("lpgl_LPLMSJ")){
				setWDCode("lpgl_LPLMSJ", "");
				if(getWDCode("lpgl_LPLMSIJ")){
					setWDCode("lpgl_LPLMSIJ", "");
				}
			}
		}
		
		if(flmid && typeof(flmid) == "string"){
			lmxxParam.flmid = flmid;
		}else{
			lmxxParam.flmid = getWDCode("lpgl_LPLMYJ")
		}
		if(lmxxParam.flmid){
			lmxxParam.lmjb = "2";
			lmxxParam.ywy = ywy;
			
			var len = getLmxx(lmxxParam, "LPLMEJ");
			if(len > 0){
				$("#lpgl_LPLMEJ").prop("disabled", false);
			}else{
				$("#lpgl_LPLMEJ").prop("disabled", true);
				lmxxParam.lmjb = "1";
			}
		}else{
			$("#lpgl_LPLMEJ").prop("disabled", true);
			$("#lpgl_LPLMSJ").prop("disabled", true);
			$("#lpgl_LPLMSIJ").prop("disabled", true);
		}
	}
	function getSjlpml(flmid){
		if(getWDCode("lpgl_LPLMSJ")){
			setWDCode("lpgl_LPLMSJ", "");
			if(getWDCode("lpgl_LPLMSIJ")){
				setWDCode("lpgl_LPLMSIJ", "");
			}
		}
		
		if(flmid && typeof(flmid) == "string"){
			lmxxParam.flmid = flmid;
		}else{
			lmxxParam.flmid = getWDCode("lpgl_LPLMEJ");
		}
		if(lmxxParam.flmid){
			lmxxParam.lmjb = "3";
			lmxxParam.ywy = ywy;
			
			var len = getLmxx(lmxxParam, "LPLMSJ");
			if(len > 0){
				$("#lpgl_LPLMSJ").prop("disabled", false);
			}else{
				$("#lpgl_LPLMSJ").prop("disabled", true);
				lmxxParam.lmjb = "2";
			}
		}else{
			$("#lpgl_LPLMSJ").prop("disabled", true);
			$("#lpgl_LPLMSIJ").prop("disabled", true);
		}
	}
	function getSijlpml(flmid){
		if(getWDCode("lpgl_LPLMSIJ")){
			setWDCode("lpgl_LPLMSIJ", "");
		}
		
		if(flmid && typeof(flmid) == "string"){
			lmxxParam.flmid = flmid;
		}else{
			lmxxParam.flmid = getWDCode("lpgl_LPLMSJ")
		}
		if(lmxxParam.flmid){
			lmxxParam.lmjb = "4";
			lmxxParam.ywy = ywy;
			
			var len = getLmxx(lmxxParam, "LPLMSIJ");
			if(len > 0){
				$("#lpgl_LPLMSIJ").prop("disabled", false);
			}else{
				$("#lpgl_LPLMSIJ").prop("disabled", true);
				lmxxParam.lmjb = "3";
			}
		}else{
			$("#lpgl_LPLMSIJ").prop("disabled", true);
		}
	}
	
	function getLmxx(lmxxParam, lmxx){
		var len;
		$.ajax({
			type: "post",
			url: Constants.amUrlPath+"common/getLmxxList",
			data: JSON.stringify(lmxxParam),
			dataType: "json",
			contentType: "application/json",
			async: false,
			success: function(data){
				len = data.length;
				store.set(lmxx, JSON.stringify(data));
				selecttextInfo();
			}
		})
		return len;
	}
	
	function getLpbq(lpbq){
		$.ajax({
			type: "get",
			url: Constants.amUrlPath+"common/getCodeListByCodeClass?codeClass=LPBQ&ywy="+ywy,
			success: function(data){
				store.set("LPBQ", JSON.stringify(data));
				selecttextInfo();
				setWDCode("lpgl_LPBQ", lpbq)
			}
		})
		
	}
	
	function uploadLogo(){
		logoUploader = WebUploader.create({
			auto: false,
			fileVal:"files",
			pick:{
				id: "#hp-logo-upload",
				multiple: false
			},
			swf: "Uploader.swf",
			server: Constants.uploadUrl, //+"?ywy="+ywy,
			accept: {
				title: "Images",
				extensions: Constants.imgExt,
				mimeTypes: Constants.imgType
			},
			fileSingleSizeLimit: 15 * 1024 * 1024
		});
		logoUploader.on("fileQueued", function(file){
			logoUploader.upload()
		})
		logoUploader.on("uploadSuccess", function(file, response) {
			if(response.successFlg){
				var tpObj = response.msgObj[0];
				$(".hp-black").removeClass("hide");
				$(".hp-jtlogo-show").removeClass("hide");
				$("#logoImg").attr("src", Constants.imageUrl+tpObj.fileId)
				var fileSize = tpObj.fileSize;
				if(fileSize < 1024*1024){
					filetime = 100;
				}else if( fileSize >= 1024*1024 &&  fileSize < 5*1024*1024){
					filetime = 250;
				}else if( fileSize >= 5*1024*1024 &&  fileSize < 10*1024*1024){
					filetime = 1000;
				}else{
					filetime = 1500;
				}
				setTimeout(function(){getLogoSlt(tpObj)}, filetime);
			}else{
				alert("Upload failed!")
			}
			
		})
		logoUploader.on("uploadComplete", function(file){
			logoUploader.removeFile(file);
		})
		logoUploader.on("error", function(type){
			if(type == "Q_EXCEED_NUM_LIMIT"){
				//alert("数量超过fileNumLimit的限制");
			}else if(type == "F_EXCEED_SIZE"){
				alert("Only upload images up to 15MB!")
			}else if(type == "Q_TYPE_DENIED"){
				alert("Does not support this format!")
			}else if(type == "F_DUPLICATE"){
				//alert("上传相同文件")
			}
		})
	}
	//截取logo
	function getLogoSlt(imgObj){
		var logocj = $('#logoImg').imgAreaSelect({
			handles : true,
			aspectRatio : "25:16",
			show : true,
			minWidth: 300,
			minHeight: 192,
			persistent: true,
			x1 : 0,
			y1 : 0,
			x2 : 300,
			y2 : 192,
			onSelectEnd : function(img,selection){
				var width =parseFloat($("#logoImg").css("width"));
				var height =parseFloat($("#logoImg").css("height"));
				$(".imgareaselect-border4").unbind("dblclick");
				$(".imgareaselect-border4").bind("dblclick",function(){
					if((selection.width == width) && (selection.height == height)){
						lpLogo = {
								tpdx : imgObj.fileSize,
								tpcc : "300*192",
								ljm : imgObj.fileName,
								wjgs : imgObj.fileExtName,
								fjdx : imgObj.fileSize,
								fjdz : imgObj.fileId
						}
					}else{
						var duploadData = {
							"scanlw" : width,
							"scanlh" : height,
							"type" : imgObj.fileExtName,
							"size" : imgObj.fileSize,
							"path" : Constants.imageUrl+imgObj.fileId, 
							"leftx" : selection.x1,
							"lefty" : selection.y1,
							"rightx" : selection.x2,
							"righty" : selection.y2,
							"selectionw" : selection.width,
							"selectionh" : selection.height,
							//ywy: ywy
						};
						$.ajax({
							type : "post",
							url : Constants.amUrlPath + "common/uploadLogo",
							contentType: 'application/json;charset=UTF-8',
							dataType: 'json',
							async : false,
							cache: false,
							data : JSON.stringify(duploadData),
							success : function(obj){
								if (typeof obj == "object") {
									if(obj.result){
										var org = jQuery.parseJSON(obj.object);
										if(org.msgObj[0].fileSize > 300 * 1024){
											alert("Image size can not exceed 300KB!");
											return false;
										}
										lpLogo = {
												tpdx : org.msgObj[0].fileSize,
												tpcc : "300*192",
												ljm : org.msgObj[0].fileName,
												wjgs : org.msgObj[0].fileExtName,
												fjdx : org.msgObj[0].fileSize,
												fjdz : org.msgObj[0].fileId
											}
									}
									else{
										manager.errorMsg(obj);
									}
								}
							},
							error: function(){
								alert("Upload failed!");
							}
						});
					}
					xglpRactive.set("lpgl.lpLogo", lpLogo);
					$(".hp-black").addClass("hide");
					$(".hp-jtlogo-show").addClass("hide");
					$("#hp-logo-upload").css("background", "url("+Constants.imageUrl+lpLogo.fjdz+") no-repeat center");
					$("#hp-logo-upload").css("background-size", "150px 96px");
					$("#logoImg").attr("src","");
					$('#logoImg').imgAreaSelect({
						remove : true
					});
					$(".imgareaselect-border4").unbind("dblclick");
				})
				
			}
		});
	}
	function uploadSlt(){
		sltUploader = WebUploader.create({
			auto: false,
			fileVal:"files",
			pick:{
				id: "#hp-cpslt-upload",
				innerHtml: "Upload local image",
				multiple: false
			},
			swf: "Uploader.swf",
			server: Constants.uploadUrl+"?ywy="+ywy,
			accept: {
				title: "Images",
				extensions: Constants.imgExt,
				mimeTypes: Constants.imgType
			},
			fileSingleSizeLimit: 15 * 1024 * 1024
		});
		sltUploader.on("fileQueued", function(file){
			if(lpsltList.length >= 10){
				alert("Only upload up to 10 images!");
				return false;
			}
			sltUploader.upload();
		})
		sltUploader.on("uploadSuccess", function(file, response){
			if(response.successFlg){
				var tpObj = response.msgObj[0];
				$(".hp-black").removeClass("hide");
				$(".hp-jtslt-show").removeClass("hide");
				$("#inputImg").attr("src", Constants.imageUrl+tpObj.fileId)
				var fileSize = tpObj.fileSize;
				if(fileSize < 1024*1024){
					filetime = 100;
				}else if( fileSize >= 1024*1024 &&  fileSize < 5*1024*1024){
					filetime = 250;
				}else if( fileSize >= 5*1024*1024 &&  fileSize < 10*1024*1024){
					filetime = 1000;
				}else{
					filetime = 1500;
				}
				setTimeout(function(){getSlt(tpObj)}, filetime);
				sltUploader.reset();
				
			}else{
				alert("Upload failed!")
			}
		})
		sltUploader.on("uploadComplete", function(file){
		})
		sltUploader.on("error", function(type){
			if(type == "Q_EXCEED_NUM_LIMIT"){
				//alert("数量超过fileNumLimit的限制");
			}else if(type == "F_EXCEED_SIZE"){
				alert("Only upload images up to 15MB!")
			}else if(type == "Q_TYPE_DENIED"){
				alert("Does not support this format!")
			}else if(type == "F_DUPLICATE"){
				alert("Uploaded!")
			}
		})
	}
	//截取缩略图
	function getSlt(imgObj){
		$('#inputImg').imgAreaSelect({
			handles : true,
			aspectRatio : "430:290",
			show : true,
			minWidth: 430,
			minHeight: 290,
			persistent: true,
			x1 : 0,
			y1 : 0,
			x2 : 430,
			y2 : 290,
			onSelectEnd : function(img,selection){
				var width =parseFloat($("#inputImg").css("width"));
				var height =parseFloat($("#inputImg").css("height"));
				$(".imgareaselect-border4").unbind("dblclick");
				$(".imgareaselect-border4").bind("dblclick",function(){
					if((selection.width == width) && (selection.height == height)){
						lpsltList.push({
						    tpdx: imgObj.fileSize,
							tpcc: "430*290",
							ljm: imgObj.fileName,
							wjgs: imgObj.fileExtName,
							fjdx: imgObj.fileSize,
							fjdz: imgObj.fileId
					    });
					}else{
						var duploadData = {
							"scanlw" : width,
							"scanlh" : height,
							"type" : imgObj.fileExtName,
							"size" : imgObj.fileSize,
							"path" : Constants.imageUrl+imgObj.fileId,
							"leftx" : selection.x1,
							"lefty" : selection.y1,
							"rightx" : selection.x2,
							"righty" : selection.y2,
							"selectionw" : selection.width,
							"selectionh" : selection.height,
							//ywy: ywy
						};
						$.ajax({
							type : "post",
							url : Constants.amUrlPath + "common/uploadLogo",
							contentType: 'application/json;charset=UTF-8',
							dataType: 'json',
							async : false,
							cache: false,
							data : JSON.stringify(duploadData),
							success : function(obj){
								if (typeof obj == "object") {
									var org = jQuery.parseJSON(obj.object);
									if(org.msgObj[0].fileSize > 300 * 1024){
										alert("Image size can not exceed 300KB!");
										return false;
									}
									if(obj.result){
										lpsltList.push({
										    tpdx : org.msgObj[0].fileSize,
										    tpcc : "430*290",
										    ljm : org.msgObj[0].fileName,
										    wjgs : org.msgObj[0].fileExtName,
										    fjdx : org.msgObj[0].fileSize,
										    fjdz : org.msgObj[0].fileId
									    });
									}else{
										manager.errorMsg(obj);
									}
								}
							}
						});
					}
					xglpRactive.set("sltList", lpsltList);
					$(".hp-black").addClass("hide");
					$(".hp-jtslt-show").addClass("hide");
					$("#inputImg").attr("src","");
					$('#inputImg').imgAreaSelect({
						remove : true
					});
					$(".imgareaselect-border4").unbind("dblclick");
				})
			}
		});
	}
	return {
		init: function(){
			loadXzlp();
		},
		getEjlpml: getEjlpml,
		getSjlpml: getSjlpml,
		getSijlpml: getSijlpml
	}
}();

$(document).ready(xzlp_app.init)
